﻿import QtQuick 2.12
import QtGraphicalEffects 1.14
import CCustomClass 1.0

// Spin版本

Item {


    id: root
    property string title: ""       // 标题文字
    property int titleDirect: 0     // 标题文字位置 0左边 1上边

    // 尺寸设置 组件的宽度和高度会根据edit和title的状态计算
    property int editWidth: 180 *dp
    property int editHeight: 40*dp
    property int titleWidth: title==="" ? 0 : (titleDirect===0 ? 80*dp : editWidth)
    property int titleHeight: title==="" ? 0 : (titleDirect===0 ? 40*dp : 30*dp)
    property var titleHAlign: Text.AlignRight       // 标题水平对齐方式
    property var titleVAlign: Text.AlignVCenter     // 标题垂直对齐方式
    property bool titleAlignJustify: true           // 标题是否两端对齐（设置为true时会覆盖titleHAline属性！！！）
    property color titleColor: "#000"

    property int spinWidth: 30*dp
    property int spinIncrement: 1       // 点一次加多少

    property bool required: false       // 前面有没有那个红色的小星号
    property bool redBorder: false      // 红框密码
    property string redInfo: ""         // 红框时下面的提示文字

    property bool editable: true
    property string defaultText: "0"
    property string prompt: ""
    property bool promptVisible: defaultText === "" ? (textinput.focus ? false : true) : false
    property var inputEchoModel: TextInput.Normal

    property var inputMaxLength: 10000
    property bool maxLengthTip: true     // 输入超过限制时是否显示提示


    property bool intflag: false
    property bool zsqflag: false
    property bool pdouflag: false
    property bool digit: false       // >0
    property bool douflag: false
    property bool ipflag: false
    property bool defpass: false

    property bool isHovered: false

    property real textLeftPadding: 10*dp
    property real textRightPadding: 10*dp   // 输入框中文字距两端的距离

    property int  editWrapModel: 0      // 0垂直居中不换行；1从上向下显示，竖着换行



    function getText(){
        return textinput.text
    }
    function setText(text){
        if(text === undefined){
            console.log("ERROR:", title, "setTextUndefined")
            return
        }
        textinput.text = text
    }
    onFocusChanged: {
        if(focus){
            textinput.forceActiveFocus()
        }
    }

    Component.onDestruction: {
        console.log("Destruction - ComboInputText")
    }


    signal textChanged()                // 文字只要改变就会触发信号
    signal textEditChanged()            // 通过用户输入触发的文字改变才会触发信号
    signal editingFinished()            // 用户结束输入时触发信号
    signal enterPressed()               // 用户按回车时触发信号

    // private ================================================================

    onVisibleChanged: {
        if(!visible){
            textinput.focus = false
        }
    }

    width: titleDirect === 0 ? (titleWidth + editWidth) : editWidth
    height: titleDirect===0 ? editHeight : (titleHeight + editHeight)

    // 标题(选填)
    Item{
        id: rectTitle
        height: titleHeight
        width: titleWidth - 16*dp       // titleWidth比用户设置的titleWidth短一点
        Text{
            id: text_title
            text: {
                if(!titleAlignJustify) return title
                else{

                    if(text_rawTitle.contentWidth === 0 || text_space.contentWidth === 0){
                        return   title
                    }

                    return funcTools.justifyAlignAppendSpace(title, parent.width, text_rawTitle.width, text_space.width)
                }
            }
            font.pixelSize: config.fontsize
            anchors.fill: parent
            color: titleColor
            verticalAlignment: titleVAlign
            horizontalAlignment: titleAlignJustify ? Text.AlignHCenter : titleHAlign
        }
        Text{           // 固定在左边的星号
            visible: required
            text: '<font color="#FF0000"">* </font>'
            x: -10*dp
            font.pixelSize: config.fontsize
            height: titleHeight
            width: 10*dp
            verticalAlignment: Text.AlignVCenter
        }
    }
    Text{           // 用来计算空格的长度
        id: text_space
        text: " "
        font.pixelSize: config.fontsize
        visible: false
    }
    Text{           // 用来计算纯文本的长度
        id: text_rawTitle
        text: title
        font.pixelSize: config.fontsize
        visible: false
    }


    // 文本框
    Rectangle{
        id: rectInput
        radius: 3*dp
        height: editHeight
        width: editWidth
        x: titleDirect===0 ? titleWidth : 0
        y: titleDirect===0 ? 0 : titleHeight
        border.color: redBorder ? "red" : (isHovered||textinput.focus ? config.themeColor : "#CCCCCC")
        Item{       // 输入框内容裁剪
            clip: true
            height: parent.height
            x: textLeftPadding
            width: parent.width - textLeftPadding-textRightPadding-4*dp - spinWidth

            Text{           // 默认文字
                text: prompt
                visible: promptVisible
                font.pixelSize: config.fontsize
                anchors.verticalCenter: parent.verticalCenter
                color: "#AAAAAA"
            }
            TextInput{
                id: textinput
                anchors.fill: parent
                font.pixelSize: config.fontsize
                verticalAlignment: TextInput.AlignVCenter
                wrapMode: root.editWrapModel===0 ? Text.NoWrap : Text.WrapAnywhere
                text: defaultText
                echoMode: inputEchoModel
                maximumLength: inputMaxLength
                Component.onDestruction: {
                    imec.onTargetDestruction()
                }
                validator: RegExpValidator {
                    regExp: defpass?/^\d{4,6}$/:pdouflag? /^[+]?[0-9]*\.?[0-9]+([eE][+]?[0-9]+)?$/ :zsqflag? /^(\d+ml.*|\d*)$/  : digit? /^[0-9]+/ : intflag? /^[-+]?\d+/ :douflag? /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/ :ipflag? /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/: /.*/
                }
                onTextChanged: {
                    if(text === ""){
                        promptVisible = true
                    }else{
                        promptVisible = false
                    }
                    root.textChanged()
                    if(focus){
//                        console.log("触发TextEditChanged")
                        textEditChanged()
                    }
                }
                onEditingFinished: {
                    root.editingFinished()
                }
                Keys.onPressed: {
//                    console.log("检测到按键事件", event.key)
                    if(Number(event.key) < 200){        // key事件在text变化事件之前判断
                        if(text.length >= maximumLength && maxLengthTip){
                            showToolTip("最多输入"+maximumLength+"个字符")
                        }
                    }if(Number(event.key) === 16777220){    // 回车
                        root.enterPressed()
                    }
                }
                onFocusChanged: {
                    if(focus){
                        root.z = 100        // 焦点时显示在上层
                    }else{
                        root.z = 0
                    }
                }
                selectByMouse: true //设置为可以被鼠标选中
            }
        }

        // 阴影
        layer.enabled: textinput.focus && config.device!==2
        layer.effect: DropShadow {
            radius: 12*dp
            samples: 43
            transparentBorder: true
            color: redBorder ? "#4DFF0000" : "#4D1677FA"
        }
    }




    InputMethodEventCatch{          // 输入法监听
        id: imec
        target: textinput
        onInputMethodEventCommitted: {
            if(textinput.text.length>=inputMaxLength && maxLengthTip){
                showToolTip("最多输入"+inputMaxLength+"个字符")
            }
        }
        onInputMethodEventPressed: {
            if(textinput.text.length>=inputMaxLength && maxLengthTip){
                showToolTip("最多输入"+inputMaxLength+"个字符")
            }
        }
        Component.onDestruction: {
            console.log("Destruction - InputMethodEventCatch")
        }
    }

    Item{       // 输入框下面的红色提示文字
        visible: redBorder
        Text{
            text: redInfo
            color: "red"
            y: root.height + 2*dp
            x: titleWidth + 2*dp
            font.pixelSize: config.fontsize - 2
        }
    }

    MouseArea{      // Hover样式
        anchors.fill: rectInput
        propagateComposedEvents: true
        hoverEnabled: config.hoverEnabled
        cursorShape: Qt.IBeamCursor
        onEntered: {
            isHovered = true && config.hoverEnabled
        }onExited: {
            isHovered = false
        }onPressed:{
            mouse.accepted = false
        }onReleased:{
            mouse.accepted = false
        }
    }

    // 不可编辑状态
    Rectangle{
        color: "#EEEEEE"
        opacity: 0.5
        visible:  ! editable
        anchors.fill: rectInput
        MouseArea{
            anchors.fill: parent
            onReleased: {
            }onClicked: {
            }
        }
    }


    // 用户输入提示 ===========================================================
    property bool isToolTipShow: false
    function showToolTip(text){
        tooltip.text = text
        tooltip.visible = true
        timerToolTip.restart()
    }
    Timer{
        id: timerToolTip
        interval: 800
        repeat: false
        triggeredOnStart: false
        onTriggered: {
            tooltip.visible = false
        }
    }
    CustomTooltip{
        id: tooltip
        delay: 0
    }


    // 右边的Spin
    Column{
        height: editHeight
        width: spinWidth
        x: parent.width - width
        y: titleDirect===0 ? 0 : titleHeight
        Item{
            height: parent.height * 0.5; width: parent.width
            Image {
                height: 11*dp; width: 11*dp
                source: "qrc:/picture/triangle_up_0.png"
                anchors.horizontalCenter: parent.horizontalCenter
                y: parent.height - height - 1
            }Rectangle{
                id: mask_0
                visible: false
                color: "#08000000"
                anchors.fill: parent
            }
            MouseArea{
                anchors.fill: parent
                hoverEnabled: true
                cursorShape: "PointingHandCursor"
                onEntered: {
                    mask_0.visible = true
                }onExited: {
                    mask_0.visible = false
                }
                onClicked: {
                    setText(Number(getText()) + spinIncrement)
                    root.textChanged()
                    root.textEditChanged()
                }
            }
        }
        Item{
            height: parent.height * 0.5; width: parent.width
            Image {
                height: 11*dp; width: 11*dp
                source: "qrc:/picture/triangle_down_0.png"
                anchors.horizontalCenter: parent.horizontalCenter
                y: 1
            }Rectangle{
                id: mask_1
                visible: false
                color: "#08000000"
                anchors.fill: parent
            }
            MouseArea{
                anchors.fill: parent
                hoverEnabled: true
                cursorShape: "PointingHandCursor"
                onEntered: {
                    mask_1.visible = true
                }onExited: {
                    mask_1.visible = false
                }
                onClicked: {
                    setText(Number(getText()) - spinIncrement)
                    root.textChanged()
                    root.textEditChanged()
                }
            }
        }
    }




}
